package com.lhy.admin.web;

import com.lhy.admin.common.mvcplus.controller.SimpleCrudControllerSupport;
import com.lhy.admin.common.mvcplus.entity.RespResult;
import com.lhy.admin.common.secure.authorization.Permissions;
import com.lhy.admin.common.treeable.Treeable;
import com.lhy.admin.common.treeable.TreeableUtil;
import com.lhy.admin.model.Department;
import com.lhy.admin.model.extend.DepartmentTree;
import com.lhy.admin.service.DepartmentService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("department")
@Permissions
public class DepartmentController extends SimpleCrudControllerSupport<DepartmentService, Department, Integer> {

    /**
     * 部门树接口
     **/
    @RequestMapping(value = "tree", method = RequestMethod.GET)
    public RespResult<List<Treeable>> tree(@Validated @ModelAttribute Department bean) {
        return RespResult.ok(TreeableUtil.toTree(service.list(bean), DepartmentTree.class));
    }


    @Override
    @Permissions("department.view")
    public RespResult<Department> get(Integer id) {
        return super.get(id);
    }

    @Override
    @Permissions("department.add")
    public RespResult<Object> create(Department bean) {
        return RespResult.create(service.createDepartment(bean));
    }

    @Permissions("department.view")
    @Override
    public RespResult validate(Department bean) {
        return super.validate(bean);
    }

    @Override
    @Permissions("department.edit")
    public RespResult update(Department bean) {
        if (bean.getParent() == null) {
            bean.setParent(0);
        }
        return super.update(bean);
    }

    @Override
    @Permissions("department.del")
    public RespResult<Object> delete(Integer id) {
        return RespResult.create(service.delDepartment(id));
    }
}
